<template>
  <Modal v-model="modal" title="奖品设置">
    <div>
      <Form :model="form" :label-width="140" ref="form" :rules="rules">
        <FormItem label="奖品名称" prop="name">
          <Input v-model.trim="form.name" placeholder="奖品名称"/>
        </FormItem>
        <FormItem label="初始库存" prop="initStock" v-if="!this.form.isComfort">
          <InputNumber :disabled="this.id ? true : false" v-model="form.initStock" precision="0" :min="1" :max="9999999999999999999999"></InputNumber>
        </FormItem>
        <FormItem label="中奖概率(%)" prop="probability" v-if="!this.form.isComfort">
          <InputNumber v-model="form.probability" precision="2" :min="0" :max="100"></InputNumber>
        </FormItem>
        <FormItem label="配图(210*210)" prop="imgUrl">
          <Input v-model="form.imgUrl" v-show="false"/>
          <PictureEditItem :uploadList="uploadList" :maxlength="1" @uploadPic="uploadPic"></PictureEditItem>
        </FormItem>
        <FormItem label="大奖" prop="isGrand" v-if="!this.form.isComfort">
          <RadioGroup v-model="form.isGrand">
            <Radio label="是">是</Radio>
            <Radio label="否">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="能中奖的门店类型" prop="storeTypeEnumList" v-if="!this.form.isComfort">
          <CheckboxGroup v-model="form.storeTypeEnumList">
            <Checkbox :label="item.value" v-for="(item, index) in storeTypeData" :key="index">{{item.text}}</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="奖品类型" prop="prizeTypeEnum">
          <RadioGroup v-model="form.prizeTypeEnum">
            <Radio label="ENTITY">实物</Radio>
            <Radio label="COUPON">现金券</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="现金券" v-if="form.prizeTypeEnum === 'COUPON'" class="require-nature">
          <Select v-model="form.couponId" filterable clearable>
            <Option v-for="item in couponList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="是否安慰奖" v-if="!this.id">
            <Checkbox v-model="form.isComfort" @on-change="onChangeComfort"><span class="font-red">如果某门店没中奖，则发放这个安慰奖给他</span></Checkbox>
        </FormItem>
      </Form>
    </div>
    <div slot="footer">
      <Button @click="modal = false" size="large" type="text">取消</Button>
      <Button :disabled="btnDisabled" @click="onSave" type="primary" size="large">确定</Button>
    </div>
</Modal>
</template>
<script>
import PictureEditItem from '@/components/PictureEditItem'
import { preFixPath } from "@/util";
import { mapGetters } from 'vuex'
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  components: {
    PictureEditItem
  },
  data() {
    const validateBig = (rule, value, callback) => {
      if (this.form.isComfort) { // 是安慰奖的话，就不用选择是否是大奖
        callback()
      } else {
        if (value === undefined || value === null) {
          callback(new Error('请选择是否是大奖'))
        } else {
          callback()
        }
      }
    }
    const validateStore = (rule, value, callback) => {
      if (this.form.isComfort) { // 是安慰奖的话，就不用选择门店
        callback()
      } else {
        if (!value.length) {
          callback(new Error('请选择门店类型'))
        } else {
          callback()
        }
      }
    }
    const validateInit = (rule, value, callback) => {
      if (this.form.isComfort) { // 是安慰奖的话，就不显示初始库存
        callback()
      } else {
        if (value === undefined || value === null) {
          callback(new Error('请输入初始库存'))
        } else if (Number(value) < 1) {
          callback(new Error('初始库存最小为1'))
        }else {
          callback()
        }
      }
    }
    const validatePro = (rule, value, callback) => {
      if (this.form.isComfort) { // 是安慰奖的话，就不显示中奖概率
        callback()
      } else {
        if (value === undefined || value === null) {
          callback(new Error('请输入中奖概率'))
        } else if (Number(value) < 0 || Number(value) > 100) {
          callback(new Error('中奖概率为0-100'))
        }else {
          callback()
        }
      }
    }
    return {
      preFixPath,
      id: null,
      lotteryId: null,
      modal: false,
      btnDisabled: false,
      isFlag: false,
      couponList: [],
      uploadList: [],
      rules: {
        isGrand: [{ required: true, validator: validateBig, trigger: "change"}],
        name: [{ required: true, message: '请输入奖品名称', trigger: "blur" }],
        initStock: [{ required: true, validator: validateInit, message: '请输入初始库存', trigger: "change" }],
        probability: [{ required: true, validator: validatePro, message: '请输入概率', trigger: "change" }],
        imgUrl: [{ required: true, message: '请上传图片', trigger: "change" }],
        prizeTypeEnum: [{ required: true, message: '请选择奖品类型', trigger: "change" }],
        storeTypeEnumList: [{required: true, type: 'array', min: 1, validator: validateStore, trigger: "change"}]
      },
      form: {
        name: '',
        initStock: null,
        probability: null,
        probabilityInit: 0,
        imgUrl: '',
        prizeTypeEnum: '',
        couponId: null,
        storeTypeEnumList: [],
        isComfort: false,
        isGrand: false
      }
    };
  },
  mounted() {
    this.$store.dispatch('getStoreType')
  },
  computed: {
    ...mapGetters(['storeTypeData'])
  },
  methods: {
    resetForm(lotteryId) {
      this.id = null
      this.$refs.form.resetFields();
      this.form = {
        name: '',
        initStock: null,
        lastStock: null,
        probability: null,
        probabilityInit: 0,
        imgUrl: '',
        prizeTypeEnum: '',
        couponId: null,
        storeTypeEnumList: [],
        isComfort:false,
        isGrand: false
      }
      this.uploadList = []
      this.lotteryId = lotteryId
      this.btnDisabled = false
      this.isFlag = this.list.some(item => item.isComfort)
      this.getAllCoupon() // 得到所有的优惠券
      this.openModal()
    },
    updateForm(id, lotteryId) {
      this.resetForm(lotteryId)
      this.id = id
      this.getInfo()
    },
    getInfo() {
      this.btnDisabled = true
      this.$ajaxGet(`/lottery/prize/${this.id}`).then(data => {
        this.btnDisabled = false
        this.form.name = data.name
        this.form.initStock = data.initStock
        this.form.lastStock = data.lastStock
        this.form.probabilityInit = data.probability
        this.form.probability = data.probability
        this.form.imgUrl = data.imgUrl
        this.uploadList = [{imgUrl: data.imgUrl, status: 'finished'}]
        this.form.prizeTypeEnum = data.prizeTypeEnum
        this.form.storeTypeEnumList = data.storeTypeEnumList
        this.form.couponId = data.prizeTypeEnum === 'COUPON' ? data.couponId : null
        this.form.isGrand = data.isGrand ? '是' : '否'
      })
    },
    onChangeComfort() {
      if (this.form.isComfort && this.isFlag) {
        this.$Modal.confirm({
          title: "提醒",
          content: "已有安慰奖，如保存一个新的安慰奖，则原安慰奖被删除，确认保存？",
          onOk: () => {
            // this.$Notice.success({
            //   title: "原安慰奖将会被替换",
            // })
          },
          onCancel: () => {
            this.form.isComfort = false
          }
        })
      }
    },
    getAllCoupon() {
      this.$ajaxGet('/coupon/coupon_info/factory_coupon').then(data => {
        this.couponList = (data || []).map(item => {
          return {
            value: item.id,
            label: item.couponName
          }
        })
      })
    },
    uploadPic(val) {
      this.form.imgUrl = val.length && val[0].imgUrl ? this.preFixPath + val[0].imgUrl : ''
    },
    openModal() {
      this.modal = true;
    },
    closeModal() {
      this.modal = false;
    },
    onSave() {
      if (this.btnDisabled) return
      this.btnDisabled = true
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.form.isComfort && this.form.storeTypeEnumList.length === 0) {
            this.$Notice.error({
              title: '错误提醒',
              desc: '请选择要中奖的门店类型'
            })
            this.btnDisabled = false
            return
          }
          let param = {
            name: this.form.name,
            initStock: this.form.initStock,
            probability: this.form.probability,
            imgUrl: this.form.imgUrl,
            prizeTypeEnum: this.form.prizeTypeEnum,
            lotteryId: this.lotteryId,
            isComfort: this.form.isComfort,
            storeTypeEnumList: this.form.isComfort ? null : this.form.storeTypeEnumList
          }
          if (this.form.prizeTypeEnum === 'COUPON') {
            if (!this.form.couponId) {
              this.$Message.error('请选择现金券')
              this.btnDisabled = false
              return
            }
            param.couponId = this.form.couponId
          }
          if (this.form.isComfort) {
            param.isGrand = false
            delete param['initStock']
            delete param['initStock']
            delete param['probability']
          } else {
            param.isGrand = this.form.isGrand === '是' ? true : false
          }
          let text = this.id ? '编辑' : '新增';
          let url = this.id ? '/lottery/prize/edit' : '/lottery/prize/save'
          if (this.id) {
            param.id = this.id
            param.lastStock = this.form.lastStock
          } else {
            param.lastStock = this.form.initStock
          }
          this.$jsonPost(url, param).then(data => {
            this.$Notice.success({
              title: `${text}成功`
            })
            this.$emit('complete')
            this.closeModal()
          }).catch(() => {
            this.btnDisabled = false
          })
        } else {
          this.btnDisabled = false
        }
      });
    }
  }
}
</script>

